import numpy as np
def pca(rdata,ndim=1):
    data = np.array(rdata, dtype=np.float32)

    r,c = data.shape
    ndim = c-ndim
    #中心化
    for i in range(c):
        data[:,i]=data[:,i] - np.mean(data[:,i])

    dataMean = np.zeros(c)
    for i in range(c):
        dataMean[i] = np.mean(data[:,i])

    COV = np.zeros((c,c))

    #处理过后的数据可以直接操作
    COV = np.dot(data.T,data)/(r-1)
    print("\t计算COV")
    print(COV)

    print("\t计算特征向量特征值:")
    W,V = np.linalg.eig(COV)

    #V 转置后 每行是一个标准化的特征向量
    print("\t\t特征值\n",W)
    print("\t\t特征向量\n",V)

    P = []
    for i in range(ndim):
        index = np.argmax(W)
        np.delete(W,index)
        P.append(V[:,index])
    P = np.array(P)

    #投影后变回元数据
    return np.dot(P,rdata.T).T
